package cn.xiaolang.thread.lock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * ReentrantReadWrite共享资源
 *
 * @author fuhw/Dean
 * @date 2020-03-06
 */
@Slf4j
public class ReadWriteResource {

    private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    public void read() {
        try {
            lock.readLock().lock();
            log.info("read start:");
            Thread.sleep(5000);
            log.info("read end!");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.readLock().unlock();
        }
    }

    public void write() {
        try {
            lock.writeLock().lock();
            log.info("write start:");
            Thread.sleep(5000);
            log.info("write end!");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.writeLock().unlock();
        }
    }
}
